﻿using Entity.Package;
using Newtonsoft.Json.Linq;
using Services;
using System;
using System.Text;
using Tools;

namespace BLL.Business
{
    /// <summary>
    /// 缴费业务处理
    /// </summary>
    public class Payment
    {
        public static void ProcessPayment(PackRequestPayment payment, CSocket.ClientThread client)
        {
            var ser = IAgentPayment.GetAgentPaymentService();

            try
            {
                string payDate = payment.PayDate.Trim();

                if (Convert.ToDecimal(payment.Yjhj) == 0 && Convert.ToDecimal(payment.PayMoney) < 5)
                {
                    PackFailReturn pkFailReturn = new PackFailReturn();
                    pkFailReturn.TradeCode = ((int)TradeCode.缴费业务).ToString();
                    pkFailReturn.ResponseCode = ((int)Common.GetNoSuccessCode(Entity.Service.ResultType.ErrorMoney)).ToString().PadLeft(3, '0');
                    pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());

                    CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

                    LogHelper.WriteInfoLog(string.Format(@"缴费金额不得低于5元，交费失败！【编号{0}；银行代码{1}；日期{2}；操作员ID{3}; 流水号{4}; 交费金额{5}】", payment.GasUserID.ToString(), "NXS", payDate,
                                                          payment.OperatorNumber.Trim(), payment.PackHead.BankWaterNumber, payment.PayMoney.Trim()));
                    return;
                }
                

                var queryReqData = new { userId = payment.GasUserID.Trim() };
                var queryResult = ser.QueryUserInfo(queryReqData);

                if (queryResult.Code == Entity.Service.ResultType.Success)
                {

                    var userInfo = queryResult.Data;

                    var payReqData = new { userId = payment.GasUserID.Trim(), payMoney = decimal.Parse(payment.PayMoney.Trim()), bankWaterNum = payment.PackHead.BankWaterNumber };
                    var payResult = ser.Pay(payReqData);

                    if (payResult.Code == Entity.Service.ResultType.Success)
                    {
                        PackReturnPaymentSuccess pkPayReturn = new PackReturnPaymentSuccess();
                        pkPayReturn.TradeCode = ((int)TradeCode.缴费业务).ToString();

                        var payResData = payResult.Data;

                        //组织正常返回包
                        pkPayReturn.ResponseCode = ((int)ResponseCode.交易成功).ToString().PadLeft(3, '0');
                        pkPayReturn.OwnFeeMoney = userInfo["userOwe"].ToString();
                        pkPayReturn.GasUserID = payment.GasUserID.ToString();
                        pkPayReturn.UserName = userInfo["userName"].ToString();
                        pkPayReturn.Address = userInfo["userAddress"].ToString();
                        pkPayReturn.LastYE = userInfo["userBalance"].ToString();
                        pkPayReturn.UserProperties = "0";
                        pkPayReturn.AccountBalance = payResData["CurrentBalance"].ToString();
                        pkPayReturn.PayMoney = payment.PayMoney;
                        pkPayReturn.CbRecordTimes = "0";
                        pkPayReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkPayReturn.ToString()).Length).ToString());
                        byte[] sendPackage = CSocket.PackageHandle.CombinationPackage(pkPayReturn);
                        if (client.Send(sendPackage))  //发送返回包
                            client.CloseSocket();//断开链接

                        LogHelper.WriteInfoLog(string.Format(@"交费成功！【编号{0}；银行代码{1}；日期{2}；操作员ID{3}; 流水号{4}; 交费金额{5}; 新结余{6}】", payment.GasUserID.ToString(), "NXS", payDate,
                                                              payment.OperatorNumber.Trim(), payment.PackHead.BankWaterNumber, payment.PayMoney.Trim(), payResData["CurrentBalance"].ToString()));
                    }
                    else
                    {
                        PackFailReturn pkFailReturn = new PackFailReturn();
                        pkFailReturn.TradeCode = ((int)TradeCode.缴费业务).ToString();
                        pkFailReturn.ResponseCode = ((int)Common.GetNoSuccessCode(payResult.Code)).ToString().PadLeft(3, '0');
                        pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());

                        CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

                        LogHelper.WriteInfoLog(string.Format(@"交费失败！【编号{0}；银行代码{1}；日期{2}；操作员ID{3}; 流水号{4}; 交费金额{5}】", payment.GasUserID.ToString(), "NXS", payDate,
                                                              payment.OperatorNumber.Trim(), payment.PackHead.BankWaterNumber, payment.PayMoney.Trim()));
                    }

                }
                else
                {
                    PackFailReturn pkFailReturn = new PackFailReturn();
                    pkFailReturn.TradeCode = ((int)TradeCode.缴费业务).ToString();
                    pkFailReturn.ResponseCode = ((int)Common.GetNoSuccessCode(queryResult.Code)).ToString().PadLeft(3, '0');
                    pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());

                    CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);

                    LogHelper.WriteErrorLog($"交费前用户{payment.GasUserID.Trim()}查询失败,返回结果：{queryResult.Code}");
                }
            }
            catch (Exception ex)
            {
                var pkFailReturn = new PackFailReturn();
                LogHelper.WriteErrorLog("ProcessPayment方法-缴费业务出现异常：" + ex.Message, ex);
                pkFailReturn.ResponseCode = ((int)ResponseCode.数据库操作错).ToString().PadLeft(3, '0');
                pkFailReturn.PackHead = new PackHead(payment.PackHead.PayWay, payment.PackHead.BankWaterNumber, (Encoding.Default.GetBytes(pkFailReturn.ToString()).Length).ToString());
                CSocket.PackageHandle.SendFailurPackage(pkFailReturn, client);
            }
        }
    }
}
